package com.igoal.dao;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.igoal.entity.DataStatus;
import com.igoal.entity.UserGoalTask;
import com.igoal.utils.CalendarUtils;

@Repository("userGoalTaskDAO")
public class UserGoalTaskDAOImpl extends
		GenericDaoHibernate<UserGoalTask, Long> implements UserGoalTaskDAO {

	public UserGoalTaskDAOImpl() {
		super(UserGoalTask.class);
	}

	public List<UserGoalTask> findByUserId(Long userId) {
		DetachedCriteria dc = DetachedCriteria.forClass(UserGoalTask.class);
		dc.add(Restrictions.eq("userGoal.pk.user.id", userId));
		getByStatus(dc, DataStatus.USING);
		
		List<UserGoalTask> tasks = findByCriteria(dc);
		
		return tasks;
	}

	public List<UserGoalTask> findByUserGoalPk(Long userId, Long goalId) {
		DetachedCriteria dc = DetachedCriteria.forClass(UserGoalTask.class);
		dc.add(Restrictions.eq("userGoal.pk.user.id", userId));
		dc.add(Restrictions.eq("userGoal.pk.goal.id", goalId));
		getByStatus(dc, DataStatus.USING);
		
		List<UserGoalTask> tasks = findByCriteria(dc);
		
		return tasks;
	}

	public List<UserGoalTask> getUnCompleteTask(Long userId, Long goalId) {
		Date today = Calendar.getInstance().getTime();
		today = CalendarUtils.getEndDate(today);
		
		DetachedCriteria dc = DetachedCriteria.forClass(UserGoalTask.class);
		
		if(userId != null)
			dc.add(Restrictions.eq("userGoal.pk.user.id", userId));
		
		if(goalId != null)
			dc.add(Restrictions.eq("userGoal.pk.goal.id", userId));
		
		dc.add(Restrictions.eq("finished", Boolean.FALSE));
		dc.add(Restrictions.lt("deadLine", today));
		getByStatus(dc, DataStatus.USING);
		
		List<UserGoalTask> tasks = findByCriteria(dc);
		
		return tasks;
	}

	public List<UserGoalTask> getTasksInPeriodTime(Long userId, Long goalId,
			Date from, Date to, boolean finished) {
		DetachedCriteria dc = DetachedCriteria.forClass(UserGoalTask.class);
		
		if(userId != null)
			dc.add(Restrictions.eq("userGoal.pk.user.id", userId));
		
		if(goalId != null)
			dc.add(Restrictions.eq("userGoal.pk.goal.id", userId));
		
		dc.add(Restrictions.eq("finished", finished));
		dc.add(Restrictions.between("deadLine", from, to));
		getByStatus(dc, DataStatus.USING);
		
		List<UserGoalTask> tasks = findByCriteria(dc);
		
		return tasks;
	}
}
